var category = "";                  // 初始类别为空


$(function () {
    var customerSex2=document.getElementById('customerSex2').value;
    if(customerSex2=='1'){
        document.getElementById('customerSex').innerHTML = '男';
    }else if(customerSex2=='2'){
        document.getElementById('customerSex').innerHTML = '女';
    }else{
        document.getElementById('customerSex').innerHTML = '未知';
    }

    $.ajax({
        url: Feng.ctxPath + "/consultant/getDoctor",
        type: "get",
        success: function (data) {
            var txt = '<option value="未指定医生">未指定医生</option>';
            for (var i = 0; i < data.length; i++) {
                txt += '<option value="' + data[i].doctor + '">' + data[i].doctor + '</option>';
            }
            document.getElementById('doctor').innerHTML = txt;
            //状态单选
            var seleteDoctorValue = $('#doctorValue').val();
            if (seleteDoctorValue != "") {
                $("#doctor option[value=" + seleteDoctorValue + "]").attr("selected", "selected");
            }
        },
        error: function (data) {
            alert('内部故障!');
        }
    });
    //初始化下拉TC列表
    $.post(Feng.ctxPath + "/tc/getLists", function (data) {
        var txt = '<option value="">--请选择现场TC--</option>';
        for (var i = 0; i < data.length; i++) {
            txt += '<option value="' + data[i].tcName + '">' + data[i].tcName + '</option>';
        }
        document.getElementById('fieldTc').innerHTML = txt;
        //状态单选
        var seletetcName = $('#tcNameValue').val();
        if (seletetcName != "") {
            $("#tcName option[value=" + seletetcName + "]").attr("selected", "selected");
        }
    }, "json");
    //初始化下拉预约项目列表
    $.post(Feng.ctxPath + "/payService/getList", function (data) {
        var txt = '';
        data.forEach(function (key,value) {
            txt  += '<div class="col-sm-4"><input type="checkbox" value="' + key.department + '" id="click_'+value+'"><label for="click_'+value+'" style="font-weight: 500;margin-left: 10px;">' + key.department + '</label></div>'
        });
        document.getElementById('projectData').innerHTML = txt;

    }, "json");


    $("#revisit").click();

});

//复诊
$("#revisit").click(function () {
    category = "revisit";
    $(this).css({'background': '#31add1','color': 'white'});
});

//持续时间操作
// function continued(obj) {
//     var time = $("#duration").val();    //获取持续时间
//     if(obj == "-"){
//         if(time == 0){
//             $("#duration").val(0);
//         }else {
//             $("#duration").val(parseInt(time) - 15);
//         }
//     }else if(obj == "+"){
//         $("#duration").val(parseInt(time) + 15);
//     }
// }




//新建患者
function addToReservations() {
    var index = layer.open({
        type: 2,
        title: '添加到店客户',
        area: ['100%', '100%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/customer/to_nature_courtyard_adds'
    });
    this.layerIndex = index;
}

var eventData;
var doctor;
var starts;
var ends;

var tiem = new Date();
var YY = tiem.getFullYear();
var MM = tiem.getMonth() + 1;
var DD = tiem.getDate();
if(MM < 10 ){
    MM = "0" + MM
}else if(DD < 10 ){
    DD = "0" + DD
}
starts = YY + "-" + MM + "-" + DD +" " + "00:00:00";
ends = YY + "-" + MM + "-" + DD +" " + "23:59:59";

$(function () {
    $('#calendars').fullCalendar({
        header: {
            left: '',
            center: '',
            right: ''
        },
        defaultView: 'agendaDay',       //进入组件默认渲染的视图
        allDaySlot: false,               //隐藏 "全天" 信息
        selectable: true,               //允许用户可以长按鼠标选择多个区域
        selectHelper: true,             //周/日视图在选择时是否预先画出“日程区块”的样式出来
        editable: false,                 //支持Event日程拖动修改，默认false
        eventLimit: true,
        nowIndicator: true,              //周/日视图中显示今天当前时间点（以红线标记）
        minTime: "08:00:00",             //周/日视图左边时间线显示的最小日期
        maxTime: "18:00:00",             //周/日视图左边时间线显示的最大日期
        titleFormat: 'YYYY-MM-DD',       //顶部title区域格式化
        slotDuration: "00:15:00",      //一格时间槽代表多长时间
        slotLabelFormat: 'HH:mm',
        selectMinDistance: 30,
        select: function (startDate, endDate, jsEvent, view, resource) {
            var start = startDate.format('YYYY-MM-DD HH:mm');
            console.log(start);
            var end = endDate.format('YYYY-MM-DD HH:mm');
            console.log(end);
            var docName = document.getElementById("doctorValue").value;
            eventData = start + "," + end + "," + docName;
        },
        timeFormat: 'H:mm',             //全局的日期显示格式(自定义成如12:00或12am等)
        slotEventOverlap: false,         //相同时间段的多个日程视觉上是否允许重叠
        slotLabelInterval: "00:30:00", //日期视图左边那一列多长间隔显示一条日期文字
        schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
        dragRevertDuration: 200,
        unselectAuto: false,
        aspectRatio: 0.6,               //宽度:高度 比例，默认1.35，
        events: function(start,end,timezone, callback) {
            start = starts;
            end = ends;
            doctor = document.getElementById('doctorValue').value;
            var timeSlot = start + "," + end + "," + doctor;
            $.ajax({
                url: Feng.ctxPath +'/doctorLooked/getDataListByDoctor/' + timeSlot,
                dataType:'json',
                type: 'POST',
                success:function(data) {
                    console.log(data);
                    var events =[];
                    $.each(data,function (key,value) {
                        if(value.arrivalStatus == '1'){//预约
                            events.push({
                                id: value.customerId,
                                title: value.appointmentPayService ,
                                start: new Date(Date.parse(value.startTime)),
                                end: new Date(Date.parse(value.endTime)),
                                customerName: value.customerName,
                                resourceId:value.id,
                                arrivalStatus:value.arrivalStatus,
                                backgroundColor:"#4bbcff",
                                borderColor:"#4bbcff"
                            });
                        }else if(value.arrivalStatus == '2'){
                            events.push({
                                id: value.customerId,
                                title: value.appointmentPayService ,
                                start: new Date(Date.parse(value.startTime)),
                                end: new Date(Date.parse(value.endTime)),
                                customerName: value.customerName,
                                resourceId:value.id,
                                arrivalStatus:value.arrivalStatus,
                                backgroundColor:"#0d4b98",
                                borderColor:"#0d4b98"
                            });
                        }else if(value.arrivalStatus == '3'){
                            events.push({
                                id: value.customerId,
                                title: value.appointmentPayService ,
                                start: new Date(Date.parse(value.startTime)),
                                end: new Date(Date.parse(value.endTime)),
                                customerName: value.customerName,
                                resourceId:value.id,
                                arrivalStatus:value.arrivalStatus,
                                backgroundColor:"#fdc42d",
                                borderColor:"#fdc42d"
                            });
                        }else if(value.arrivalStatus == '4'){
                            events.push({
                                id: value.customerId,
                                title: value.appointmentPayService ,
                                start: new Date(Date.parse(value.startTime)),
                                end: new Date(Date.parse(value.endTime)),
                                customerName: value.customerName,
                                resourceId:value.id,
                                arrivalStatus:value.arrivalStatus,
                                backgroundColor:"#2cc87e",
                                borderColor:"#2cc87e"
                            });
                        }else if(value.arrivalStatus == '5'){
                            events.push({
                                id: value.customerId,
                                title: value.appointmentPayService ,
                                start: new Date(Date.parse(value.startTime)),
                                end: new Date(Date.parse(value.endTime)),
                                customerName: value.customerName,
                                resourceId:value.id,
                                arrivalStatus:value.arrivalStatus,
                                backgroundColor:"#87d127",
                                borderColor:"#87d127"
                            });
                        }
                    });
                    callback(events);
                }
            });
        },
        eventRender: function (calEvent,element, view) {//在呈现事件时触发
            if(calEvent.customerName == ""||calEvent.customerName == null){
                element.prepend("<div class='myfc-title'><span>新建预约</span></div>");
            }else {
                element.prepend("<div class='myfc-title'><span>"+calEvent.customerName+"</span></div>");
            }
        }
    });
    laydate.render({
        elem: '#calendarDocument',
        position: 'static',
        done:function (value, date, endDate) {
            var start = value + " " + "00:00:00";
            var end = value + " " + "23:59:59";
            $("#startDocumentValue").val(start);
            $("#endDocumentValue").val(end);
            doctor = document.getElementById('doctorValue').value;
            starts = document.getElementById('startDocumentValue').value;
            ends = document.getElementById('endDocumentValue').value;
            $('#calendars').fullCalendar( 'gotoDate', value );
            $('#calendars').fullCalendar( 'refetchEvents' );
        }
    });
});

function refreshChange() {
    document.getElementById('doctorValue').value = $("#doctor").val();
    $('#calendars').fullCalendar( 'refetchEvents' );
}
//提交
function submission() {
    var startTimeValue = eventData.split(",")[0];
    var endTimeValue = eventData.split(",")[1];
    var customerPhone = document.getElementById("customerPhone").innerHTML;
    var fieldTc = document.getElementById("fieldTc").value;
    var doctor = document.getElementById("doctor").value;
    var remarks = document.getElementById("remarks").value;
    var reservationsId = document.getElementById("reservationsId").value;
    var customerId = document.getElementById("customerId").value;
    var check = $("input[type='checkbox']:checked");

    var projectData = "" ;
    for(var i = 0; i < check.length ; i++ ){
        projectData += $(check[i]).val() + ",";
    }
    // var  customerStatus = "复诊";
        $.ajax({
            url: Feng.ctxPath +"/customer/addCustomerFzs",
            type: "post",
            data: {
                "reservationsId": reservationsId,
                "endTimeValue":endTimeValue,
                "startTimeValue":startTimeValue,
                // "customerStatus":customerStatus,
                "customerPhone": customerPhone,
                "customerId": customerId,
                "projectData": projectData,
                "fieldTc": fieldTc,
                "doctor": doctor,
                "remarks": remarks
            },
            success: function (data) {
                console.log(data);
                if(data==11){
                    alert('预约时间必须大于当日!');
                }else{
                    alert('预约成功!');
                    $('#calendars').fullCalendar( 'refetchEvents' );
                    parent.layer.close(parent.layer.getFrameIndex(window.name))
                }
            },
            error: function (data) {
                alert('预约失败!');
            }
        });

}
